package main

import (
	"fmt"
	"sync"
	"time"
)

func Run() {
	defer wg.Done()
	for i := 0; i < 10; i++ {
		fmt.Println("Hello", i)
	}
}
func Sum(s []int, c chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	}
	c <- sum // 把 sum 发送到通道 c
}

func MakeGoroutine() {
	go Run()
	var input string
	fmt.Scanln(&input)
}
func MakeChannel() {
	c := make(chan int)
	var s []int = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
	go Sum(s[:len(s)/2], c)
	go Sum(s[len(s)/2:], c)
	x, y := <-c, <-c
	fmt.Println(x + y)
}
func MakeChannel2() {
	c := make(chan int, 2)
	c <- 1
	fmt.Println(cap(c), len(c))
}
func CloseChannel() {
	c := make(chan int, 5)
	c <- 1
	c <- 2
	c <- 3
	c <- 4
	c <- 5
	close(c)
	for i := range c {
		fmt.Println(i)
	}

}

var wg sync.WaitGroup

func TestWaitGroup() {
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go Run()
	}
	wg.Wait()
	fmt.Println("全部goroutine已经结束")
}

func TestClose(c <-chan int) {
	for i := range c {
		fmt.Println(i)
	}
}
func TestBlock() {
	c := make(chan int, 5)
	go TestClose(c)
	time.Sleep(time.Second * 4)
	c <- 1
	c <- 2
	close(c)

}
